package com.hotau.setting;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.hotau.HotauConstants;
import com.hotau.R;
import com.hotau.framework.NeedLogin;
import com.hotau.member.service.MemberService;
import com.hotau.push.PushService;
import com.hotau.util.DialogUtil;
import com.hotau.util.HttpUtil;
import com.hotau.util.PreferencesUtils;

/**
 * 系统设置
 * 
 * @author hanshengliang
 * @data 2011-12-10
 * @version 1.0
 *          <ul>
 *          <li>1.0 创建</li>
 *          </ul>
 */
public class SettingNotifyFragment extends Fragment implements OnClickListener,
		NeedLogin {

	public static final String TAG = "SettingNotifyFragment";
	private ImageView setting_btn_receive_on = null;
	private ImageView setting_btn_receive_off = null;
	private ImageView setting_btn_voice_on = null;
	private ImageView setting_btn_voice_off = null;
	private ImageView setting_btn_time = null;
	private TextView setting_time_value = null;
	private static String ON = "1";
	private static String OFF = "0";
	private static String mTimes[];

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		initAllWidget();
		initAllEvent();
		// 取值
		String receive = PreferencesUtils.getReceive(getActivity());
		String voice = PreferencesUtils.getVoice(getActivity());
		String times = PreferencesUtils.getTimes(getActivity());
		Log.d(TAG, "receive :" + receive);
		if (ON.equals(receive)) {
			setting_btn_receive_on.setVisibility(View.GONE);
			setting_btn_receive_off.setVisibility(View.VISIBLE);
		} else {
			setting_btn_receive_on.setVisibility(View.VISIBLE);
			setting_btn_receive_off.setVisibility(View.GONE);
		}
		if (ON.equals(voice)) {
			setting_btn_voice_on.setVisibility(View.VISIBLE);
			setting_btn_voice_off.setVisibility(View.GONE);
		} else {
			setting_btn_voice_on.setVisibility(View.GONE);
			setting_btn_voice_off.setVisibility(View.VISIBLE);
		}
		mTimes = getActivity().getResources().getStringArray(
				R.array.setting_times);
		int indexTimes = 0;
		if (times != null && Integer.parseInt(times) >= 0) {
			indexTimes = Integer.parseInt(times);
		}
		setting_time_value.setText(mTimes[indexTimes]);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.setting_notify_view, container, false);
	}
	
	public String pushSwitchService(String pushSwitch) {
		
        String usrCode = MemberService.getUserCode(SettingNotifyFragment.this.getActivity());
        String terminalCode = HotauConstants.getTerminalCode(SettingNotifyFragment.this.getActivity());
        String terminalType = "1";
        String request = "Form:userCode=" + usrCode + ";pushSwitch=" +
        	pushSwitch + ";icloudToken=Android;terminalCode=" + terminalCode + ";terminalType=" + terminalType;
        
		String result = HttpUtil.doHttp(60000, 60000, HotauConstants.PUSH_SWITCH_URL,
                request, HttpUtil.HTTP_POST, HttpUtil.UTF8_ENCODING, false);
		
		return result;
	}

	@Override
	public void onClick(View v) {
		
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.setting_notify_receive_on:
		    v.post(new Runnable()
            {
                @Override
                public void run()
                {
                	if(!HttpUtil.hasInternet(getActivity())) {
                		DialogUtil.alertDialog(getActivity(), "系统网络连接错误，开启通知失败!");
                		return;
                	}
                	
                    String result = pushSwitchService("Y");
        			Log.d(TAG, "Turn on push switch, the callback result is :" 
        					+ result);
        			try {
	        			JSONObject switchResult = new JSONObject(result);
	        			if (switchResult != null && switchResult.getInt("result") == 1) {
	        				Intent serviceOn = new Intent(getActivity(), PushService.class);
	                        getActivity().stopService(serviceOn);
	                        getActivity().startService(serviceOn);
	                        
		                    PreferencesUtils.setReceive(getActivity(), ON);
		                    setting_btn_receive_on.setVisibility(View.GONE);
		                    setting_btn_receive_off.setVisibility(View.VISIBLE);
		                    
		                    Log.d(TAG,
		                            "PreferencesUtils receive on:"
		                                    + PreferencesUtils.getReceive(getActivity()));
	        			} else {
	        				if (switchResult != null)
	        					Log.d(TAG, "开启推送功能失败;errorCode=" 
	        							+ switchResult.getInt("errorCode") 
	        								+ ";errorMsg=" + switchResult.getString("errorMsg"));
	        				
	        				DialogUtil.alertDialog(getActivity(), "系统繁忙，请稍后再试!");
	        			}
        			} catch (JSONException e) {
        				
        			}
                }
            });
			break;
		case R.id.setting_notify_receive_off:
			if(!HttpUtil.hasInternet(getActivity())) {
        		DialogUtil.alertDialog(getActivity(), "系统网络连接错误，关闭通知失败!");
        		return;
        	}

			String result = pushSwitchService("N");
			Log.d(TAG, "Turn on push switch, the callback result is :" 
					+ result);
			try {
				JSONObject switchResult = new JSONObject(result);
				if (switchResult != null && switchResult.getInt("result") == 1) {
					
					Intent serviceOff = new Intent(getActivity(), PushService.class);
					getActivity().stopService(serviceOff);
					
					PreferencesUtils.setReceive(getActivity(), OFF);
					setting_btn_receive_on.setVisibility(View.VISIBLE);
					setting_btn_receive_off.setVisibility(View.GONE);
					Log.d(TAG,
							"PreferencesUtils receive off:"
									+ PreferencesUtils.getReceive(getActivity()));
				} else {
					if (switchResult != null)
						Log.d(TAG, "关闭推送功能失败;errorCode=" 
								+ switchResult.getInt("errorCode")
									+ ";errorMsg=" + switchResult.getString("errorMsg"));
					DialogUtil.alertDialog(getActivity(), "系统繁忙，请稍后再试!");
				}
			} catch (JSONException e) {
				
			}
			
			break;
		case R.id.setting_notify_voice_on:
			PreferencesUtils.setVoice(getActivity(), ON);
			setting_btn_voice_on.setVisibility(View.GONE);
			setting_btn_voice_off.setVisibility(View.VISIBLE);
			break;
		case R.id.setting_notify_voice_off:
			PreferencesUtils.setVoice(getActivity(), OFF);
			setting_btn_voice_on.setVisibility(View.VISIBLE);
			setting_btn_voice_off.setVisibility(View.GONE);
			break;
		case R.id.setting_time_icon:
			// DialogUtil.showDialog(getActivity(), "", "用户名必须填写。");
			break;
		default:
			break;
		}
	}

	/**
	 * 初始化所有控件
	 */
	public void initAllWidget() {
		setting_btn_receive_on = (ImageView) getActivity().findViewById(
				R.id.setting_notify_receive_on);
		setting_btn_receive_off = (ImageView) getActivity().findViewById(
				R.id.setting_notify_receive_off);
		setting_btn_voice_on = (ImageView) getActivity().findViewById(
				R.id.setting_notify_voice_on);
		setting_btn_voice_off = (ImageView) getActivity().findViewById(
				R.id.setting_notify_voice_off);
		setting_btn_time = (ImageView) getActivity().findViewById(
				R.id.setting_time_icon);
		setting_time_value = (TextView) getActivity().findViewById(
				R.id.setting_time_value);
	}

	/**
	 * 初始化所有事件
	 */
	public void initAllEvent() {
		setting_btn_receive_on.setOnClickListener(this);
		setting_btn_receive_off.setOnClickListener(this);
		setting_btn_voice_on.setOnClickListener(this);
		setting_btn_voice_off.setOnClickListener(this);
		setting_btn_time.setOnClickListener(this);
	}
}
